#include "./select.hpp"
#include "./render_select.hpp"
#include "./select_cmd.hpp"

namespace qbe::select {

void select_cmd_init(ecs::Query query, ecs::Commands commands, ecs::Bus& bus) {
  auto& cell = query.get_resource<qlib::Cell::s_ptr>();
  auto& lib = query.get_resource<qlib::Library::s_ptr>();
  auto& layer_manager = query.get_resource<layer::Manager>();

  SelectCmd selectcmd = SelectCmd(cell, layer_manager);
  commands.insert_resource(selectcmd);
}

std::vector<layout::CellQuad::Node> select_filter(entt::registry& reg, ecs::Query query, std::vector<layout::CellQuad::Node> sel_nodes) {
  std::vector<layout::CellQuad::Node> result;
  auto& model = query.get_resource<SelectModel>();
  if (model.select_ele_ctrl == 0)
    return sel_nodes;

  if (model.select_ele_ctrl == 1) {
    for (auto i : sel_nodes) {
      auto _ptr = reg.try_get<qlib::Path::s_ptr>(i.entity);
      if (_ptr == nullptr)
        continue;
      auto line = *_ptr;
      if (line->spine.points.size() == 2)
        result.push_back(i);
    }
  } else if (model.select_ele_ctrl == 2) {
    for (auto i : sel_nodes) {
      auto _ptr = reg.try_get<qlib::Path::s_ptr>(i.entity);
      if (_ptr == nullptr)
        continue;
      auto line = *_ptr;
      if (line->spine.points.size() > 2)
        result.push_back(i);
    }
  }
  return result;
}

// 扫描鼠标周围的对象
void scan_nodes() {}

void clear_event(ecs::Query query) {
  query.get_resource<ecs::Event<select::Event>>().clear();
}

void SelectPlugin::build(ecs::App& app) {
  app.init_event<select::Event>();

  app.init_resource<HoverModel>(HoverModel{});
  app.init_resource<SelectModel>(SelectModel{});
  app.init_resource<SelectPartModel>(SelectPartModel{});
  app.init_resource<OverallModel>(OverallModel{});

  app.add_plugins<RenderSelectPlugin>(RenderSelectPlugin{});

  app.add_stage<OverallUpdateStage>();
  app.add_stage<PartUpdateStage>();
  app.add_stage<PreUpdateStage>();

  app.add_systems<ecs::stage::Startup>(select_cmd_init);

  app.add_systems<PreUpdateStage>(overall_update);
  app.add_systems<ecs::stage::Last>(clear_event);
}

}  // namespace qbe::select